package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.model.AccessToken;
import com.example.demo.model.User;
import com.example.demo.service.AccessTokenService;
import com.example.demo.service.UserService;

@Controller
public class LoginController {

	@Autowired
	private AccessTokenService accessTokenService;
	
	@Autowired
	private UserService userService;
	
	@PostMapping("dologin")
	@ResponseBody
	public Object test(@RequestBody User user) {
		System.out.println("用户正在请求dologin，username : " + user.getUsername());
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("code", 20000);
		try {
			if(StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
				throw new Exception("账号密码不能为空");
			}
			//验证登录账号和密码的准确性
			String username = user.getUsername();//登录账号
			User userCurrent = userService.findByUsername(username);
			if(userCurrent == null) {
				throw new Exception("账号不存在");
			}else if(!user.getPassword().equals(userCurrent.getPassword())){
				throw new Exception("密码错误");
			}else {
				//...
			}
			Map<String,Object> tokenMap = new HashMap<String,Object>();
			String randomUUID = UUID.randomUUID().toString();//产生随机数作为token
			
			AccessToken myAccessToken = new AccessToken();
			myAccessToken.setAccessToken(randomUUID);
			myAccessToken.setUsername(username);
			myAccessToken.setScope("all");
			result.put("message", myAccessToken);
			//将对应的realname的AccessToken保存至服务器，将myAccessToken入库
			accessTokenService.create(myAccessToken);
			//重新申请accessTolen之后需要将旧的数据清除掉
			//...
			//生成返回值
			tokenMap.put("token", randomUUID);
			result.put("data", tokenMap);
		} catch (Exception e) {
			result.put("code", 1);
			result.put("message", e.getMessage());
			System.out.println("登录操作失败："+user.getRealname());
		}
		return result;
	}
	
	@PostMapping("logout")
	@ResponseBody
	public Object logout(HttpServletRequest request) {
		String token = request.getHeader("X-Token");
		System.out.println("用户正在请求logout，token : " + token);
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("code", 20000);
		try {
			accessTokenService.deleteByToken(token);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 1);
			result.put("message", e.getMessage());
		}
		return result;
	}
	
}
